package com.zzy.common.utils.guanmai;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSONObject;
import com.zzy.common.core.redis.RedisCache;
import com.zzy.common.utils.EmailUtil;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.SecureRandom;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 功能描述:
 *
 * @author zhouzhiyong
 * @date 2024/07/19 23:10
 */
@Component
public class GuanmaiCommon {
    private static final Logger log = LoggerFactory.getLogger(GuanmaiCommon.class);
    private static String apiUrl;
    private static String appId;
    private static String appSecret;
    private static String guanmaiTokenKey;
    private static int guanmaiExpireTime;
    private static String chongqingUser;
    private static String chongqingUserPass;
    private static String chongqingClient;
    private static String chongqingClientSecret;
    private static String chongqingUserUrl;
    private static  EmailUtil mailUtil;
    @Value("${api.guanmaiurl}")
    private String url;
    // 注入 RedisCache 对象
    private static RedisCache redisCache;
    @Value("${api.appId}")
    private    String guanmaiAppId;
    @Value("${api.appSecret}")
    private    String guanmaiAppSecret;
    @Value("${api.guanmaiTokenKey}")
    private    String tokenKey;

    @Value("${api.chongqingUsername}")
    private    String chongqingUsername;
    @Value("${api.chongqingPassword}")
    private    String chongqingPassword;
    @Value("${api.clientId}")
    private    String  clientId;
    @Value("${api.clientSecret}")
    private    String  clientSecret;
    @Value("${api.chongqingUrl}")
    private    String chongqingUrl;
    // 注入配置文件中的观麦令牌过期时间（单位：分钟）
    @Value("${api.guanmaiExpireTime}")
    private   int expireTime;
    @Autowired
    private RedisCache injectedRedisCache;

    public GuanmaiCommon(EmailUtil mailUtil) {
        this.mailUtil = mailUtil;
    }

    @PostConstruct
    public void init() {
        guanmaiExpireTime=expireTime;
        guanmaiTokenKey=tokenKey;
        appSecret=guanmaiAppSecret;
        apiUrl = url;
        appId = guanmaiAppId;
        redisCache = injectedRedisCache;
        chongqingUserUrl = chongqingUrl;
        chongqingUser = chongqingUsername;
        chongqingUserPass = chongqingPassword;
        chongqingClient=clientId;
        chongqingClientSecret=clientSecret;
    }
    // 观麦访问令牌
    private static String accessToken;
    private static String chongqingToken;
    // 注入配置文件中的观麦令牌在 Redis 中的键名




    public static String getGuanmaiToken() {
        if(redisCache.hasKey(guanmaiTokenKey)){
            return redisCache.getCacheObject(guanmaiTokenKey);
        }
        try {
            sendRequestWithURL("/v1/api/auth/access_token/get/1.0", createGuanmaiTokenRequestBody(), false, null, "guanmai");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return accessToken;
    }
    public static String getChongqingToken() {
        if(redisCache.hasKey("chongqingToken")){
            return redisCache.getCacheObject("chongqingToken");
        }
        try {
            Map<String, Object> params=new HashMap<>();
            params.put("username",chongqingUser);
            params.put("password",chongqingUserPass);
            params.put("client_id",chongqingClient);
            params.put("client_secret",chongqingClientSecret);
            params.put("grant_type","password");
            params.put("scope","server");
            sendChongqingToken("/api/oauth2/token",params);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return chongqingToken;
    }
    /**
     * 发送请求到观麦系统 获取 采购订单列表。
     *
     * @param urlAddress 请求的 URL 地址后缀
     */
    public static String sendRequestGet(Map<String, Object> paramMap, String urlAddress) {
        String reponse = "";
        accessToken = getGuanmaiToken();
        paramMap.put("access_token",accessToken);
        try {
            reponse = sendGetRequestWithURL(urlAddress, paramMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return reponse;
    }


    private static String sendGetRequestWithURL(String urlSuffix, Map<String, Object> paramMap) throws Exception {
        // 使用Hutool的HttpUtil工具类拼接参数到URL上，形成完整的请求URL
        // 构建包含参数的完整URL字符串
        String fullUrl = buildFullUrlWithParams(apiUrl+urlSuffix, paramMap);

        // 发送GET请求并获取响应，这里只是简单打印响应状态码和响应内容示例，实际可能需要更深入处理响应
        String response = HttpRequest.get(fullUrl).execute().body();
        System.out.println("Response Code: " + HttpRequest.get(fullUrl).execute().getStatus());
        System.out.println("Response Body: " + response);
        return response;
    }
    private static String buildFullUrlWithParams(String apiUrl, Map<String, Object> paramMap) {
        if (paramMap.isEmpty()) {
            return apiUrl;
        }

        StringBuilder urlBuilder = new StringBuilder(apiUrl);
        if (!apiUrl.contains("?")) {
            urlBuilder.append("?");
        } else {
            urlBuilder.append("&");
        }

        boolean firstParam = true;
        for (Map.Entry<String, Object> entry : paramMap.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();
            if (value!= null) {
                if (!firstParam) {
                    urlBuilder.append("&");
                }
                urlBuilder.append(key).append("=").append(HttpUtil.encodeParams(value.toString(), CharsetUtil.CHARSET_UTF_8));
                firstParam = false;
            }
        }

        return urlBuilder.toString();
    }
    /**
     * 使用指定的 URL 后缀、请求体、是否添加通用请求头等参数发送请求到观麦系统。
     *
     * @param urlSuffix        URL 地址后缀
     * @param body             请求体字符串
     * @param addCommonHeaders 是否添加通用请求头
     * @param token            访问令牌
     * @throws Exception 如果在处理过程中出现异常则抛出
     */
    private static String sendRequestWithURL(String urlSuffix, String body, boolean addCommonHeaders, String token, String platform) throws Exception {
        String sendUrl = "";
        if (platform.equals("guanmai")) {
            sendUrl = apiUrl;
        }
        URL url = new URL(sendUrl + urlSuffix);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        if (platform.equals("guanmai")) {
            if (addCommonHeaders) {
                con.setRequestProperty("Access-Token", token);
                con.setRequestProperty("Nonce-Str", generate19DigitRandomNumber());
                con.setRequestProperty("Time-Stamp", String.valueOf(System.currentTimeMillis()));
                con.setRequestProperty("Group-Id", "536378520826283032");
            }

        }
        con.setRequestProperty("Content-Type", "application/json");

        con.setDoOutput(true);

        DataOutputStream out = new DataOutputStream(con.getOutputStream());
        out.writeBytes(body);
        out.flush();
        out.close();

        int responseCode = con.getResponseCode();
        System.out.println("Response Code : " + responseCode);

        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuilder response = new StringBuilder();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        if (!addCommonHeaders && (platform.equals("guanmai")||platform.equals("youquan"))) {
            // 处理响应获取令牌
            processTokenResponse(response.toString());
            redisCache.setCacheObject(guanmaiTokenKey,accessToken,guanmaiExpireTime, TimeUnit.MINUTES);
        }
        return response.toString();
    }


    /**
     * 生成 19 位随机数字字符串。
     *
     * @return 19 位随机数字字符串
     */
    public static String generate19DigitRandomNumber() {
        SecureRandom random = new SecureRandom();
        long min = (long) Math.pow(10, 18);
        long max = (long) Math.pow(10, 19) - 1;
        long randomNumber = min + (long) (random.nextDouble() * (max - min));
        return String.valueOf(randomNumber);
    }

    /**
     * 创建获取令牌的请求体。
     *
     * @return 请求体字符串
     */
    private static String createGuanmaiTokenRequestBody() {
        JSONObject json = new JSONObject();
        json.put("appid", appId);
        json.put("secret", appSecret);
        return json.toString();
    }

    /**
     * 处理令牌响应，从响应中提取令牌并赋值给成员变量。
     *
     * @param response 令牌响应字符串
     */
    private static void processTokenResponse(String response) {
        // 解析响应获取 accessToken，并赋值给成员变量
        JSONObject jsonResponse = JSONObject.parseObject(response);
        JSONObject dataObject = jsonResponse.getJSONObject("data");
        accessToken = dataObject.getString("access_token");
    }
    //推送观麦订单
    public static  String pushGuanmaiOrder(String json,String orderUrl){
        HttpResponse response = HttpRequest.post(apiUrl+orderUrl)
                .header("Content-Type", "application/json") // 设置请求头，表明发送的是JSON数据
                .body(json) // 设置请求体，传入JSON格式的字符串
                .execute();

        // 获取响应状态码
        int statusCode = response.getStatus();
        System.out.println("响应状态码: " + statusCode);

        // 获取响应内容（可以根据实际响应格式进行进一步处理，比如也是JSON格式则进行解析等）
        String responseBody = response.body();
        System.out.println("响应内容: " + responseBody);
        return responseBody;
    }
    //发送邮件
    public static void doSomethingAndSendMail(String toEmail,String title,String content) {
        // 调用工具类的方法发送邮件，这里收件人、主题和正文根据实际情况填写
        log.info("发送邮件至:"+toEmail+",邮件头:"+title+"邮件内容："+content);
        mailUtil.sendMail(toEmail, title, content);
    }
    public static String sendChongqingToken(String url,Map<String, Object> params) throws Exception {
        // 创建POST请求实例，并设置更多属性，这里设置超时时间为5000毫秒（5秒）
        HttpRequest request = HttpRequest.post(chongqingUserUrl+url)
                .header("Content-Type", "application/x-www-form-urlencoded")
                .form(params)
                .timeout(5000)
                .charset(CharsetUtil.CHARSET_UTF_8);

        try {
            HttpResponse response = request.execute();
            int responseCode = response.getStatus();
            if(responseCode==200){
                processChongqingTokenResponse(response.body());
            }
            System.out.println("Response Code: " + responseCode);
            String responseBody = response.body();
            System.out.println("Response Body: " + responseBody);
        } catch (Exception e) {
            e.printStackTrace();
        }
        redisCache.setCacheObject("chongqingToken",chongqingToken,guanmaiExpireTime, TimeUnit.MINUTES);
        return chongqingToken;
    }
    public static String pushChongqing(String url,String json) throws Exception {
        String responseBody="";
        if(redisCache.hasKey("chongqingToken")){
            chongqingToken=redisCache.getCacheObject("chongqingToken");
        }else{
            getChongqingToken();
        }
        // 创建POST请求实例，并设置更多属性，这里设置超时时间为5000毫秒（5秒）
        HttpRequest request = HttpRequest.post(chongqingUserUrl+url)
                .header("Content-Type", "application/json")
                .header("Authorization","Bearer "+chongqingToken)
                .body(json)
                .timeout(5000)
                .charset(CharsetUtil.CHARSET_UTF_8);

        try {
            HttpResponse response = request.execute();
            int responseCode = response.getStatus();
            System.out.println("Response Code: " + responseCode);
             responseBody = response.body();
            System.out.println("Response Body: " + responseBody);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return responseBody;
    }
    private static void processChongqingTokenResponse(String response) {
        // 解析响应获取 accessToken，并赋值给成员变量
        JSONObject jsonResponse = JSONObject.parseObject(response);
        chongqingToken = jsonResponse.getString("access_token");
    }

}
